package com.ruoyi.quartz.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.quartz.domain.ImapEmailInfo;
import com.ruoyi.quartz.service.MailSeduService;
import com.ruoyi.system.domain.SysMail;
import com.ruoyi.system.domain.SysMailConf;
import com.ruoyi.system.mapper.SysMailMapper;
import com.ruoyi.system.service.ISysMailConfService;
import com.ruoyi.system.service.ISysMailService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.search.FlagTerm;
import java.io.*;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

@Service
public class MailSeduServiceImpl implements MailSeduService {

    @Resource
    private ISysMailConfService sysMailConfService;

    @Resource
    private ISysMailService sysMailService;

    @Resource
    private SysMailMapper sysMailMapper;

    @Override
    public void receiveMail() throws Exception {
        List<SysMailConf> sysMailConfList = sysMailConfService.selectSysMailConfList(null);
        if (sysMailConfList != null && sysMailConfList.size() > 0) {
            for (int m = 0; m < sysMailConfList.size(); m++) {
                SysMailConf sysMailConf = sysMailConfList.get(m);
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";//ssl加密

                // 定义连接imap服务器的属性信息
                String port = "993";
                String imapServer = sysMailConf.getHostname();
                String protocol = "imap";

                //有些参数可能不需要
                Properties props = new Properties();
                props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
                props.setProperty("mail.imap.socketFactory.fallback", "false");
                props.setProperty("mail.transport.protocol", protocol); // 使用的协议
                props.setProperty("mail.imap.port", port);
                props.setProperty("mail.imap.socketFactory.port", port);

                //创建会话
                Session session = Session.getInstance(props, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(sysMailConf.getUserName(),
                                sysMailConf.getPwd());
                    }
                });
                //存储对象
                Store store = session.getStore("imap");
                //连接
                store.connect(imapServer,993,sysMailConf.getUserName(),sysMailConf.getPwd());
                Folder folder = null;
                try {
                    // 获得收件箱
                    folder = store.getFolder("INBOX");
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                    //false 表示未读
                    FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN),true);
                    //获得收件箱的邮件列表
                    Message[] messages = folder.search(flagTerm);
                    // 打印不同状态的邮件数量
                    System.out.println("收件箱中共" + messages.length + "封邮件!");
                    System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
                    System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
                    System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");

                    System.out.println("------------------------开始解析邮件----------------------------------");
                    String fPath = RuoYiConfig.getUploadPath();
                    List<ImapEmailInfo> result = new ArrayList<>();
                    if (messages.length <= 0) {

                    } else {
                        parseEmail(sysMailConf, result,messages);
                    }
//                    for (int i = 0; i < messages.length; i++) {
////                        System.out.println("消息:"+messages[i].getSubject());
////                        String from = MimeUtility.decodeText(messages[i].getFrom()[0].toString());
////                        InternetAddress internetAddress = new InternetAddress(from);
////                        System.out.println("发件人：" + internetAddress.getPersonal() + '(' + internetAddress.getAddress() + ')');
//                        MimeMessage msg = (MimeMessage) messages[i];
//
//                        String from = MimeUtility.decodeText(messages[i].getFrom()[0].toString());
//                        InternetAddress ia = new InternetAddress(from);
//                        System.out.println("发件人：" + ia.getPersonal() + '(' + ia.getAddress() + ')');
//                        System.out.println("主题：" + messages[i].getSubject());
//                        System.out.println("邮件发送时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(messages[i].getSentDate()));
//                        boolean isContainerAttachment = isContainAttachment(msg);
//                        System.out.println("是否包含附件：" + isContainerAttachment);
////                        if (isContainerAttachment) {
////                            //设置需要保存的目录并保存附件
////                            saveAttachment(msg,
////                                    fPath + File.separator + sysMailConf.getUserId() + File.separator
////                                            + "_"+i+"_"); //保存附件
////                        }
//                        messages[i].setFlag(Flags.Flag.SEEN, true);
//                    }
                } catch (NoSuchProviderException e) {
                    e.printStackTrace();
                } catch (MessagingException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (folder != null) {
                            folder.close(false);
                        }
                        if (store != null) {
                            store.close();
                        }
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {

        }
    }

    /**
     * 解析邮件并返回
     * @param result
     * @param messages
     */
    private void parseEmail(SysMailConf sysMailConf,
                                   List<ImapEmailInfo> result,
                                   Message[] messages) throws Exception {
        for(Message message : messages){
            MimeMessage msg = (MimeMessage) message;
            ImapEmailInfo emailInfo = new ImapEmailInfo();
            emailInfo.setSubject(MimeUtility.decodeText(msg.getSubject()));
            emailInfo.setSender(getSenderAddress(msg));
            StringBuffer content = new StringBuffer();
            String contentType = msg.getContentType();
            if (contentType.toLowerCase().startsWith("text/plain")) {
                getHtmlContent(msg, content, true);
            } else {
                getHtmlContent(msg, content, false);
            }
            emailInfo.setContent(content.toString());
            System.out.println(MimeUtility.decodeText(msg.getSubject()));
            System.out.println(getSenderAddress(msg));
            System.out.println(content.toString());
            System.out.println("邮件发送时间:" +
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                            .format(msg.getSentDate()));
            result.add(emailInfo);
            //同一个时间，同一个主题，不需要重复插入
            SysMail sysMailSearch = new SysMail();
            sysMailSearch.setType(1);
            sysMailSearch.setTitle(MimeUtility.decodeText(msg.getSubject()));
            sysMailSearch.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(msg.getSentDate()));
            List<SysMail> sysMailList = sysMailService.selectSysMailList(sysMailSearch);
            if (sysMailList != null && sysMailList.size() > 0) {

            } else {
                SysMail sysMail = new SysMail();
                sysMail.setContent(content.toString());
                sysMail.setTitle(MimeUtility.decodeText(msg.getSubject()));
                sysMail.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(msg.getSentDate()));
                sysMail.setUserId(sysMailConf.getUserId());
                sysMail.setFromMail(getSenderAddress(msg));
                sysMail.setToMail(sysMailConf.getUserName());
                sysMail.setType(1);
                sysMail.setCreateTime(new Date());
                sysMail.setCreateBy("CronTab");
                sysMailMapper.insertSysMail(sysMail);
            }
        }
    }

    //获取邮件发件人address
    private String getSenderAddress(MimeMessage msg) throws Exception {
        Address[] froms = msg.getFrom();
        if (froms.length < 1)
            throw new MessagingException("没有发件人!");
        InternetAddress address = (InternetAddress) froms[0];
        if(address != null){
            return address.getAddress();
        }
        return null;
    }

    //获取邮件内的HTML内容
    private void getHtmlContent(Part part, StringBuffer content,boolean plainFlag) throws MessagingException, IOException {
        //如果是文本类型的附件，通过getContent方法可以取到文本内容，但这不是我们需要的结果，所以在这里要做判断
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/html") && !isContainTextAttach && plainFlag == false) {
            content.append(MimeUtility.decodeText(part.getContent().toString()));
        } else if (part.isMimeType("text/plain") && !isContainTextAttach && plainFlag) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getHtmlContent((Part) part.getContent(), content, plainFlag);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getHtmlContent(bodyPart, content, plainFlag);
            }
        }
    }

    /**
     * 判断邮件中是否包含附件
     * @param
     * @return 邮件中存在附件返回true，不存在返回false
     * @throws MessagingException
     * @throws Exception
     */
    public boolean isContainAttachment(Part part) throws Exception {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }

                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }

                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part)part.getContent());
        }
        return flag;
    }

    /**
     * 保存附件
     * @param part 邮件中多个组合体中的其中一个组合体
     * @param destDir  附件保存目录
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void saveAttachment(Part part, String destDir) throws Exception{
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart,destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(),destDir);
        }
    }

    /**
     * 读取输入流中的数据保存至指定目录
     * @param is 输入流
     * @param fileName 文件名
     * @param destDir 文件存储目录
     * @throws Exception
     */
    private void saveFile(InputStream is, String destDir, String fileName)
            throws Exception {
        //如果文件名称包含关键字则进行保存
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        int len = -1;
        while ((len = bis.read()) != -1) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解码
     * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
     * @return 解码后的文本
     * @throws UnsupportedEncodingException
     */
    public String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }
}
